package com.xmmj.baselibrary.base.activity.permission

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import androidx.annotation.StringRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.xmmj.baselibrary.R
import com.xmmj.baselibrary.base.activity.swipeback.SwipeBackActivity
import com.xmmj.baselibrary.widget.permission.PermissionDialog
import io.reactivex.functions.Action
import java.lang.Exception
import java.util.ArrayList

/**
 * 支持权限申请的Activity
 */
open class PermissionActivity : SwipeBackActivity() {
    //权限申请成功后的回调
    private var mSuccessAction: Action? = null

    //权限取消后的回调
    private var mCancelAction: Action? = null

    //权限描述信息
    private var mDescription: String? = null

    //权限列表
    private val mPermissions: MutableList<String> = ArrayList()

    companion object {
        //协议头以及请求码
        private const val MY_PERMISSIONS_REQUEST = 1001
        private const val PACKAGE_URL_SCHEME = "package:"
        private const val REQUEST_CODE_REQUEST_SETTING = 1027
    }

    /**
     * 请求权限
     *
     * @param permissions   权限列表
     * @param successAction 权限申请成功后的回调
     * @param cancelAction  权限取消后的回调
     * @param description   需要这些权限的原因（当用户拒绝之后，会提示这个原因）
     */
    open fun requestPermission(
        permissions: Array<String>,
        successAction: Action,
        cancelAction: Action,
        @StringRes description: Int
    ) {
        requestPermission(
            permissions,
            successAction,
            cancelAction,
            resources.getString(description)
        )
    }

    /**
     * 请求权限
     *
     * @param permissions   权限列表
     * @param successAction 权限申请成功后的回调
     * @param cancelAction  权限取消后的回调
     * @param description   需要这些权限的原因（当用户拒绝之后，会提示这个原因）
     */
    open fun requestPermission(
        permissions: Array<String>,
        successAction: Action,
        cancelAction: Action?,
        description: String?
    ) {
        //遍历检查所有的权限是否未授权
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                mPermissions!!.add(permission)
            }
        }

        //全部已授权
        if (mPermissions.size <= 0) {
            try {
                successAction.run()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return
        }

        //遍历检查权限申请是否需要再次提醒
        var needRationale = false
        for (p in mPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                needRationale = true
                break
            }
        }
        mCancelAction = cancelAction
        mSuccessAction = successAction
        mDescription = description
        if (needRationale) {
            //需要再次提醒，弹窗提示
            val dialog = PermissionDialog()
            dialog.setTitle(getString(R.string.permission_application))
            dialog.setContent(description)
            dialog.setOnConfirmListener {
                ActivityCompat.requestPermissions(
                    this,
                    mPermissions.toTypedArray(),
                    MY_PERMISSIONS_REQUEST
                )
                it.dismiss()
            }
            dialog.show(supportFragmentManager, PermissionDialog::class.java.name)
        } else {
            //无需再次提醒，直接申请
            ActivityCompat.requestPermissions(
                this,
                mPermissions.toTypedArray(),
                MY_PERMISSIONS_REQUEST
            )
        }
    }

    /**
     * 请求权限之后的回调处理
     *
     * @param requestCode  请求码
     * @param permissions  权限列表
     * @param grantResults 授权结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        try {
            if (requestCode == MY_PERMISSIONS_REQUEST) {
                //遍历检查授权结果
                var allGranted = true
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allGranted = false
                        break
                    }
                }
                if (allGranted) {
                    //全部授权，执行成功回调
                    if (mSuccessAction != null) mSuccessAction!!.run()
                } else {
                    //有未授权权限，需要弹窗提示前往设置页面
                    val dialog = PermissionDialog()
                    dialog.setTitle(getString(R.string.permission_application_failed))
                    dialog.setContent(getString(R.string.go_to_Settings, mDescription))
                    dialog.setOnConfirmListener { d ->
                        startAppSettings(this)
                        d.dismiss()
                    }
                    dialog.setOnCancelListener { d ->
                        d.dismiss()
                        try {
                            if (mCancelAction != null) {
                                mCancelAction!!.run()
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                    dialog.show(supportFragmentManager, PermissionDialog::class.java.name)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 返回该页面时的回调处理
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        参数
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
                //遍历检查未授权权限
                val list: MutableList<String> = ArrayList()
                for (permission in mPermissions!!) {
                    if (ContextCompat.checkSelfPermission(
                            this,
                            permission
                        ) == PackageManager.PERMISSION_DENIED
                    ) {
                        list.add(permission)
                    }
                }
                if (list.size > 0) {
                    //有未授权权限，需要弹窗提示前往设置页面
                    val dialog = PermissionDialog()
                    dialog.setTitle(getString(R.string.permission_application_failed))
                    dialog.setContent(getString(R.string.go_to_Settings, mDescription))
                    dialog.setOnConfirmListener { d ->
                        startAppSettings(this)
                        d.dismiss()
                    }
                    dialog.setOnCancelListener { d ->
                        d.dismiss()
                        try {
                            if (mCancelAction != null) {
                                mCancelAction!!.run()
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                    dialog.show(supportFragmentManager, PermissionDialog::class.java.name)
                } else {
                    //全部授权，则执行成功回调
                    if (mSuccessAction != null) mSuccessAction!!.run()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 跳转到设置页面去设置权限
     *
     * @param activity 上下文
     */
    private fun startAppSettings(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse(PACKAGE_URL_SCHEME + activity.packageName)
        activity.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING)
    }
}